import { camelize, isObject } from "./utils";

function inserted(el, binding) {
  const callback = binding?.value;
  if (callback) window.addEventListener("resize", callback);
  el._onResize = callback;
}

function unbind(el) {
  if (!el._onResize) return;
  window.removeEventListener("resize", el._onResize);
  delete el._onResize;
}

function getStyle(
  element,
  styleName,
) {
  if (!element || !styleName) return null;
  styleName = camelize(styleName);
  if (styleName === "float") {
    styleName = "cssFloat";
  }
  try {
    const style = element.style[styleName];
    if (style) return style;
    const computed = document.defaultView.getComputedStyle(element, "");
    return computed ? computed[styleName] : "";
  } catch (e) {
    return element.style[styleName];
  }
};

function setStyle(
  element,
  styleName,
  value,) {
  if (!element || !styleName) return;

  if (isObject(styleName)) {
    Object.keys(styleName).forEach(prop => {
      setStyle(element, prop, styleName[prop]);
    });
  } else {
    styleName = camelize(styleName);
    element.style[styleName] = value;
  }
};

function removeStyle(element, style) {
  if (!element || !style) return;

  if (isObject(style)) {
    Object.keys(style).forEach(prop => {
      setStyle(element, prop, "");
    });
  } else {
    setStyle(element, style, "");
  }
};

export {
  inserted,
  unbind,
  removeStyle,
  setStyle,
  getStyle
};
